<template>
	<div class="comment-container">
		<!-- 发布评论 -->
		<el-card class="publish-comment">
			<el-input type="textarea" :rows="3" placeholder="发表评论" v-model="newComment.content"></el-input>
			<single-upload class="marginT5 marginB5" v-model="newComment.imageUrls" :maxSendSize="30"
				:showTip="false"></single-upload>
			<el-button type="success" @click="submitComment" size="mini">发布</el-button>
		</el-card>

		<!-- 一级评论列表 -->
		<el-card v-for="comment in topLevelComments" :key="comment.commentId" class="top-level-comment"
			v-loading="loadingTopLevel">
			<div class="comment-header">
				<el-avatar :src="comment.userAvatar" />
				<span class="username">{{ comment.userName }}</span>
				<span class="comment-time">{{CommentFormatTime(comment.createTime)}}</span>
			</div>
			<div class="comment-content">
				<div v-html="comment.content"></div>
				<div v-if="comment.imageUrls">
					<el-image v-for="url in comment.imageUrls.split(',')" :key="url" :src="url+'?w=100&h=100&q=75'"
						class="comment-image" fit="cover" :preview-src-list="[url]"></el-image>
				</div>
			</div>
			<div class="actions">
				<!-- 根据二级评论数量决定是否显示“展开二级评论”按钮 -->
				<el-button v-if="comment.replyCount > 0" type="text" @click="toggleReplies(comment.commentId)">
					{{ repliesExpanded[comment.commentId] ? '收起' : '展开' }}
				</el-button>
				<el-button type="text" @click="likeComment(comment.commentId,comment)"><i
						class="iconfont icon-xihuancopy"></i>({{comment.likeCount}})</el-button>
				<el-button type="text" @click="deleteComment(comment.commentId)" v-show="storeUserinfo.Id==comment.userId">删除</el-button>
				<el-button type="text" @click="showReplyBox(comment.commentId, comment.userName,$event)">回复</el-button>
			</div>
			<!-- 二级评论列表 -->
			<div v-if="repliesExpanded[comment.commentId] && replies[comment.commentId] && replies[comment.commentId].length > 0"
				:key="`replies-${comment.commentId}`">
				<el-card v-for="reply in replies[comment.commentId]" :key="reply.commentId"
					:class="`reply-comment-${reply.commentId}`">
					<div class="reply-header">
						<el-avatar :src="reply.userAvatar" />
						<span class="username">{{ reply.userName }}</span>
						<span class="comment-time">{{CommentFormatTime(comment.createTime)}}</span>
					</div>
					<div class="reply-content">
						<div v-html="reply.content"></div>
						<div v-if="reply.imageUrls">
							<el-image v-for="url in reply.imageUrls.split(',')" :key="url" :src="url"
								class="comment-image" fit="cover"></el-image>
						</div>
					</div>
				</el-card>
				<!-- 加载更多二级评论 -->
				<div class="textCenter">
					<el-button v-if="replyPage[comment.commentId] < replyTotalPages[comment.commentId]" type="text"
						@click="loadMoreReplies(comment.commentId)">
						加载更多
					</el-button>
					<el-button  type="text"
						@click="toggleReplies(comment.commentId)">
						收起
					</el-button>
				</div>
			</div>
		</el-card>
		<!-- 加载更多一级评论 -->
		<div class="textCenter">
			<el-button v-if="topLevelPage < topLevelTotalPages" type="text" @click="loadMoreTopLevelComments">
				加载更多
			</el-button>
		</div>
		<!-- 悬浮回复组件 -->
		<div class="editBox" v-if="replyBoxVisible">
			<el-dialog :title="`回复@${replyParentuserName}`" :visible.sync="replyBoxVisible" width="80%" center
				:modal="false">
				<div class="textCenter">
					<el-card>
						<el-input type="textarea" :rows="3" placeholder="回复评论" v-model="replyContent"></el-input>
					</el-card>
				</div>
				<span slot="footer" class="dialog-footer">
					<el-button class="boderr18" @click="hideReplyBox">取 消</el-button>
					<el-button class="boderr18" type="primary" @click="submitReply">回 复</el-button>
				</span>
			</el-dialog>
		</div>
		<!-- <div v-if="replyBoxVisible" class="reply-box" v-clickaway="hideReplyBox" :style="{
        top: replyBoxPosition.y + 'px',
        left: replyBoxPosition.x + 'px'
      }">
			<el-card>
				<el-input type="textarea" :rows="3" placeholder="回复评论" v-model="replyContent"></el-input>
				<el-button type="primary" @click="submitReply" size="mini">回复</el-button>
			</el-card>
		</div> -->
	</div>
</template>

<script>
	import {
		directive
	} from 'vue-clickaway';
	import {
		formatTime
	} from "@/utils/base"
	import {
		getTopLevelComments,
		getReplyComments,
		addComment,
		likeComment,
		deleteComment
	} from "@/api/comment";
	import SingleUpload from "@/components/Upload/singleUpload";
	import {
		debounce
	} from "@/utils/common.js";
	import {
		createPopper
	} from "@popperjs/core";

	export default {
		name: "MobileStateComment",
		components: {
			SingleUpload
		},
		directives: {
			clickaway: directive
		},
		props: {
			stateId: {
				type: Number,
				required: true
			}
		},
		data() {
			return {
				topLevelComments: [], // 一级评论
				topLevelPage: 1, // 当前一级评论页码
				topLevelLimit: 10, // 每页加载的一级评论数量
				topLevelTotalPages: 1, // 一级评论总页数
				replies: {}, // 二级评论
				replyPage: {}, // 每个一级评论下的二级评论页码
				replyLimit: 10, // 每页加载的二级评论数量
				replyTotalPages: {}, // 二级评论总页数
				newComment: {
					content: "",
					imageUrls: ""
				}, // 新评论内容
				loadingTopLevel: false, // 一级评论加载状态
				repliesExpanded: {}, // 控制二级评论的展开和收起状态
				replyBoxVisible: false, // 回复组件是否显示
				replyContent: "", // 回复内容
				replyParentId: null, // 当前回复的父评论ID
				replyBoxPosition: {
					x: 0,
					y: 0
				} // 回复组件的位置
			};
		},
		async mounted() {
			await this.loadTopLevelComments(1); // 初始加载第一页一级评论
		},
		computed: {
			// 创建一个 Map，将 commentId 映射到数组索引
			commentIdToIndexMap() {
				return new Map(this.topLevelComments.map((comment, index) => [comment.commentId, index]));
			},
			storeUserinfo() {
				return this.$store.getters.userInfo;
			}
		},
		methods: {
			CommentFormatTime(date) {
				return formatTime(date)
			},
			updateReplyCount(targetCommentId, newReplyCount) {
				// 通过 Map 快速查找目标 commentId 的索引
				const index = this.commentIdToIndexMap.get(targetCommentId);
				if (index !== undefined) {
					// 使用 Vue.set 确保更新是响应式的
					this.$set(this.topLevelComments[index], "replyCount", newReplyCount);
				} else {
					console.log(`Comment with commentId ${targetCommentId} not found.`);
				}
			},
			async loadTopLevelComments(page) {
				this.loadingTopLevel = true; // 开始加载
				const res = await getTopLevelComments({
					stateId: this.stateId,
					page,
					limit: this.topLevelLimit
				});
				this.loadingTopLevel = false; // 结束加载
				if (res.code === 200) {
					if (page === 1) {
						this.topLevelComments = [...res.data]; // 初始加载
					} else {
						this.topLevelComments = [...this.topLevelComments, ...res.data]; // 追加加载
					}
					this.topLevelPage = page;
					this.topLevelTotalPages = res.totalPage // 总页数
				}
			},
			async loadMoreTopLevelComments() {
				await this.loadTopLevelComments(this.topLevelPage + 1);
			},
			async loadReplies(parentId, page) {
				const loading = this.$loading({
					target: `.reply-comment-${parentId}`, // 指定加载动画的目标区域
					background: "rgba(255, 255, 255, 0.8)"
				});
				const res = await getReplyComments({
					parentId,
					page,
					limit: this.replyLimit
				});
				loading.close(); // 关闭加载动画
				if (res.code === 200) {
					if (!this.replies[parentId]) {
						this.$set(this.replies, parentId, []); // 初始加载
					}
					if (page === 1) {
						this.$set(this.replies, parentId, res.data); // 初始加载
					} else {
						this.replies[parentId] = [...this.replies[parentId], ...res.data]; // 追加加载
					}
					this.replyPage[parentId] = page;
					this.replyTotalPages[parentId] = res.totalPage; // 总页数
				}

			},
			async loadMoreReplies(parentId) {
				await this.loadReplies(parentId, this.replyPage[parentId] + 1);
			},
			toggleReplies(parentId) {
				this.$set(this.repliesExpanded, parentId, !this.repliesExpanded[parentId]); // 初始加载
				if (!this.repliesExpanded[parentId]) {
					// 如果收起二级评论，清空二级评论数据
					this.replies[parentId] = [];
				} else {
					// 如果展开二级评论，加载二级评论
					this.loadReplies(parentId, 1);
				}
			},
			showReplyBox(parentId, replyParentUserName, event) {
				this.replyParentId = parentId;
				this.replyParentuserName = replyParentUserName;
				this.replyBoxVisible = true;
				this.replyContent = ""; // 清空回复内容
				// // 设置悬浮回复组件的位置
				// this.replyBoxPosition.x = event.clientX - 10;
				// this.replyBoxPosition.y = event.clientY - 10;
			},
			hideReplyBox() {
				this.replyBoxVisible = false;
			},
			async submitReply() {
				if (!this.replyContent.trim()) return;
				const res = await addComment({
					stateId: this.stateId,
					parentId: this.replyParentId,
					content: this.replyContent
				});
				if (res.code === 200) {
					this.replyContent = "";
					this.hideReplyBox();
					await this.loadReplies(this.replyParentId, 1); // 刷新二级评论
					if (!this.repliesExpanded[this.replyParentId]) {
						this.updateReplyCount(this.replyParentId, 1)
						this.$set(this.repliesExpanded, this.replyParentId, !this.repliesExpanded[this
							.replyParentId]); // 初始加载
					}
				}
			},
			async submitComment() {
				if (!this.newComment.content.trim()) return this.$message.warning("不能发布空评论");;
				const res = await addComment({
					stateId: this.stateId,
					content: this.newComment.content,
					imageUrls: this.newComment.imageUrls
				});
				if (res.code === 200) {
					this.newComment.content = "";
					this.newComment.imageUrls = "";
					await this.loadTopLevelComments(1); // 刷新一级评论列表
				}
			},
			likeComment: debounce(async function(commentId,comment) {
				const res = await likeComment({
					commentId
				});
				if (res.code === 200) {
					this.$message.success("点赞成功");
					comment.likeCount++;
					// await this.loadTopLevelComments(this.topLevelPage); // 刷新评论列表
				}
			}),
			deleteComment: debounce(function(commentId) {
				this.$confirm("确认要删除该评论？", "提示", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning",
					})
					.then(async () => {
						const res = await deleteComment({
							commentId
						});
						if (res.code === 200) {
							this.$message.success("删除成功");
							await this.loadTopLevelComments(this
								.topLevelPage); // 刷新评论列表
						}
					})
					.catch(() => {});

			})
		}
	};
</script>

<style scoped>
	.comment-container {
		padding: 20px;
		background: #f5f5f5;
		/* position: relative; */
	}

	.publish-comment {
		margin-bottom: 20px;
	}

	.comment-header {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.reply-header {
		display: flex;
		align-items: center;
		margin-bottom: 10px;
	}

	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		margin-right: 10px;
	}

	.username {
		font-weight: bold;
		margin: 0 5px;
	}

	.comment-time {
		font-size: 10px;
		color: #bdc2e8;
	}

	.comment-content {
		margin-top: 10px;
	}

	.comment-image {
		width: 100px;
		height: 100px;
		margin-right: 10px;
	}

	.actions {
		margin-top: 10px;
	}

	.reply-comment {
		margin-left: 40px;
		margin-top: 10px;
	}

	.el-card {
		margin-bottom: 10px;
	}

	.reply-box {
		position: absolute;
		z-index: 100;
		background: white;
		border: 1px solid #ddd;
		padding: 10px;
		border-radius: 5px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	}

	.editBox :deep(.el-dialog) {
		width: 80% !important;
		background-image: linear-gradient(to top, #bdc2e8 0%, #bdc2e8 1%, #e6dee9 100%);
		border-radius: 8px;
	}
</style>